/** 存储类型 */
import { StorageType } from '../enum'

/**
 * 存储空间类
 *
 * @description 封装了 localStorage 和 sessionStorage 的常用操作方法。
 * @example
 * const storage = new LocalStorage(StorageType.Local)
 * storage.setItem('user', { name: 'Alice' })
 * const user = storage.getItem<{ name: string }>('user')
 * storage.removeItem('user')
 */
class StorageSpace {
  private storage: Storage

  constructor(type: StorageType) {
    if (type === StorageType.Local) {
      this.storage = localStorage
    } else {
      this.storage = sessionStorage
    }
  }

  /**
   * 写入存储
   *
   * @param key 键
   * @param value 值
   */
  setItem<T>(key: string, value: T): void {
    try {
      const serializedValue = JSON.stringify(value)
      this.storage.setItem(key, serializedValue)
    } catch (error) {
      window.console.error('set storage error: ', error)
    }
  }

  /**
   * 读取存储
   *
   * @param key 键
   * @returns
   */
  getItem<T>(key: string): T | null {
    try {
      const serializedValue = this.storage.getItem(key)
      if (serializedValue === null) {
        return null
      }
      return JSON.parse(serializedValue) as T
    } catch (error) {
      window.console.error('get storage error: ', error)
      return null
    }
  }

  /**
   * 删除存储
   *
   * @param key 键
   */
  removeItem(key: string): void {
    try {
      this.storage.removeItem(key)
    } catch (error) {
      window.console.error('remove storage error: ', error)
    }
  }

  /**
   * 清空存储
   */
  clear(): void {
    this.storage.clear()
  }
}

export default StorageSpace
